package jmine.tec.aom.validator;

import java.util.List;

import jmine.tec.aom.AOMMessages;
import jmine.tec.aom.domain.AbstractPropertyValue;
import jmine.tec.aom.domain.PropertyType;
import bancosys.tec.persist.validator.AbstractValidator;
import bancosys.tec.persist.validator.ValidationError;
import bancosys.tec.utils.reflection.ReflectionUtils;

/**
 * Validates that the class given in the {@link PropertyType} is visible.
 * 
 * @author jrenaut
 */
public class PropertyTypeValidator extends AbstractValidator<PropertyType> {

    /**
     * {@inheritDoc}
     */
    @Override
    public final List<ValidationError> validateInsert(PropertyType bean) {
        return this.addError(super.validateInsert(bean), this.validate(bean));
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public final List<ValidationError> validateUpdate(PropertyType bean) {
        return this.addError(super.validateUpdate(bean), this.validate(bean));
    }

    /**
     * @param pt the {@link PropertyType}
     * @return a {@link ValidationError} if the property value class is not visible
     */
    private ValidationError validate(PropertyType pt) {
        try {
            Class<?> clazz = ReflectionUtils.findClass(pt.getPropertyValueClass());
            if (!AbstractPropertyValue.class.isAssignableFrom(clazz)) {
                return new ValidationError(AOMMessages.INVALID_PROPERTY_VALUE_CLASS.create(pt, pt.getPropertyValueClass()));
            }
        } catch (ClassNotFoundException e) {
            return new ValidationError(AOMMessages.PROPERTY_VALUE_CLASS_NOT_FOUND.create(pt, pt.getPropertyValueClass()));
        }
        return null;
    }

}
